<template>
  <div class="coupon-center-page">
    <!-- 顶部导航栏 -->
    <Navbar />

    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">
          <el-icon :size="32" class="title-icon"><Ticket /></el-icon>
          优惠券中心
        </h1>
        <p class="page-subtitle">领取优惠券，享受更多优惠</p>
      </div>

      <!-- 优惠券列表 -->
      <div class="coupon-list" v-loading="loading">
        <el-empty v-if="!loading && couponList.length === 0" description="暂无可领取的优惠券" />

        <div class="coupon-grid">
          <div 
            v-for="coupon in couponList" 
            :key="coupon.couponId"
            class="coupon-card"
            :class="getCouponClass(coupon)"
          >
            <div class="coupon-left">
              <div class="coupon-amount">
                <template v-if="coupon.couponType === '0'">
                  <span class="amount-symbol">¥</span>
                  <span class="amount-value">{{ coupon.discountAmount }}</span>
                </template>
                <template v-else-if="coupon.couponType === '1'">
                  <span class="amount-value">{{ (coupon.discountRate * 10).toFixed(1) }}</span>
                  <span class="amount-unit">折</span>
                </template>
                <template v-else>
                  <span class="amount-text">免费</span>
                </template>
              </div>
              <div class="coupon-condition">
                满{{ coupon.minAmount }}可用
              </div>
            </div>

            <div class="coupon-right">
              <div class="coupon-info">
                <h3 class="coupon-name">{{ coupon.couponName }}</h3>
                <div class="coupon-meta">
                  <el-tag :type="getCouponTypeTag(coupon.couponType)" size="small">
                    {{ getCouponTypeName(coupon.couponType) }}
                  </el-tag>
                  <span v-if="coupon.couponType === '1'" class="max-discount">
                    最高优惠¥{{ coupon.maxDiscountAmount }}
                  </span>
                </div>
                <div class="coupon-time">
                  <el-icon><Clock /></el-icon>
                  {{ formatTime(coupon.startTime) }} ~ {{ formatTime(coupon.endTime) }}
                </div>
                <div class="coupon-stock">
                  <span>剩余 {{ coupon.remainCount }}/{{ coupon.totalCount }}</span>
                  <span class="limit-tip">每人限领{{ coupon.limitPerUser }}张</span>
                </div>
              </div>

              <div class="coupon-action">
                <el-button 
                  type="primary"
                  :disabled="coupon.remainCount <= 0"
                  :loading="receivingMap[coupon.couponId]"
                  @click="handleReceive(coupon)"
                >
                  {{ coupon.remainCount <= 0 ? '已抢光' : '立即领取' }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getAvailableCoupons, receiveCoupon } from '@/api/coupon'
import { ElMessage } from 'element-plus'
import { Ticket, Clock } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'
import dayjs from 'dayjs'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const couponList = ref([])
const receivingMap = reactive({})

// 加载优惠券列表
const loadCoupons = async () => {
  loading.value = true
  try {
    const data = await getAvailableCoupons()
    couponList.value = data || []
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 领取优惠券
const handleReceive = async (coupon) => {
  // 检查是否登录
  if (!userStore.isLoggedIn()) {
    ElMessage.warning('请先登录')
    return
  }

  if (coupon.remainCount <= 0) {
    ElMessage.warning('该优惠券已被抢光')
    return
  }

  receivingMap[coupon.couponId] = true
  try {
    await receiveCoupon(coupon.couponId)
    ElMessage.success('领取成功')
    // 重新加载列表
    loadCoupons()
  } catch (error) {
    console.error('领取失败:', error)
    // 错误信息已在拦截器中处理
  } finally {
    receivingMap[coupon.couponId] = false
  }
}

// 获取优惠券类型名称
const getCouponTypeName = (type) => {
  const typeMap = {
    '0': '满减券',
    '1': '折扣券',
    '2': '免费券'
  }
  return typeMap[type] || '优惠券'
}

// 获取优惠券类型标签
const getCouponTypeTag = (type) => {
  const tagMap = {
    '0': 'danger',
    '1': 'warning',
    '2': 'success'
  }
  return tagMap[type] || 'info'
}

// 获取优惠券样式类
const getCouponClass = (coupon) => {
  if (coupon.remainCount <= 0) {
    return 'coupon-sold-out'
  }
  return `coupon-type-${coupon.couponType}`
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD')
}

onMounted(() => {
  loadCoupons()
})
</script>

<style scoped>
.coupon-center-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
  margin: 0 0 10px 0;
}

.title-icon {
  color: #ff4d4f;
}

.page-subtitle {
  font-size: 16px;
  color: #666;
  margin: 0;
}

.coupon-list {
  min-height: 400px;
}

.coupon-grid {
  display: grid;
  gap: 20px;
}

.coupon-card {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  display: flex;
  transition: all 0.3s;
  position: relative;
}

.coupon-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.coupon-card::before {
  content: '';
  position: absolute;
  left: 180px;
  top: -5px;
  bottom: -5px;
  width: 10px;
  background: radial-gradient(circle at left, transparent 5px, white 5px);
  background-size: 10px 10px;
  background-position: left center;
}

.coupon-left {
  width: 180px;
  background: linear-gradient(135deg, #ff6b6b 0%, #ff4d4f 100%);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30px 20px;
}

.coupon-type-1 .coupon-left {
  background: linear-gradient(135deg, #ffa940 0%, #ff7a45 100%);
}

.coupon-type-2 .coupon-left {
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
}

.coupon-sold-out .coupon-left {
  background: linear-gradient(135deg, #999 0%, #666 100%);
}

.coupon-amount {
  display: flex;
  align-items: baseline;
  margin-bottom: 10px;
}

.amount-symbol {
  font-size: 24px;
  font-weight: bold;
}

.amount-value {
  font-size: 48px;
  font-weight: bold;
  line-height: 1;
}

.amount-unit {
  font-size: 24px;
  font-weight: bold;
  margin-left: 4px;
}

.amount-text {
  font-size: 36px;
  font-weight: bold;
}

.coupon-condition {
  font-size: 14px;
  opacity: 0.9;
}

.coupon-right {
  flex: 1;
  padding: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin: 0 0 12px 0;
}

.coupon-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.max-discount {
  font-size: 12px;
  color: #999;
}

.coupon-time {
  font-size: 14px;
  color: #666;
  display: flex;
  align-items: center;
  gap: 5px;
  margin-bottom: 8px;
}

.coupon-stock {
  font-size: 13px;
  color: #999;
  display: flex;
  align-items: center;
  gap: 15px;
}

.limit-tip {
  color: #ff4d4f;
}

.coupon-action {
  margin-left: 20px;
}

.coupon-sold-out {
  opacity: 0.6;
}

@media (max-width: 768px) {
  .coupon-card {
    flex-direction: column;
  }

  .coupon-card::before {
    left: -5px;
    right: -5px;
    top: 140px;
    bottom: auto;
    width: auto;
    height: 10px;
    background: radial-gradient(circle at top, transparent 5px, white 5px);
    background-size: 10px 10px;
    background-position: center top;
  }

  .coupon-left {
    width: 100%;
    padding: 20px;
  }

  .coupon-right {
    flex-direction: column;
    align-items: flex-start;
  }

  .coupon-action {
    margin-left: 0;
    margin-top: 15px;
    width: 100%;
  }

  .coupon-action .el-button {
    width: 100%;
  }
}
</style>
